package com.xvaca.spcms.servlet.admin.channel;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xvaca.spcms.bean.ChannelBean;
import com.xvaca.spcms.dao.ChannelDAO;

/**
 * Servlet implementation class ChannelAddServlet
 */
public class ChannelAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String path = request.getContextPath();
		String syncPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/receive/id";
		
		request.setAttribute("syncURL", syncPath);
		request.getRequestDispatcher("channel_add.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		String name = request.getParameter("name"); // 通道名称
		String cmd = request.getParameter("cmd"); // 指令
		String code = request.getParameter("code"); // 长号码
		String syncUrl = request.getParameter("syncURL"); // 状态同步地址
		String price = request.getParameter("price"); // 结算价格
		String ip = request.getParameter("ip"); // IP地址
		String status = request.getParameter("status"); // 状态
		String desc = request.getParameter("desc"); // 描述
		
		String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		
		ChannelBean channel = new ChannelBean();
		channel.setCmd(cmd);
		channel.setCode(code);
		channel.setCreatedAt(currentTime);
		channel.setDesc(desc);
		channel.setIp(ip);
		channel.setName(name);
		channel.setPrice(Integer.parseInt(price));
		channel.setStatus(Integer.parseInt(status));
		channel.setSyncUrl(syncUrl);
		channel.setUpdatedAt(currentTime);
		
		ChannelDAO dao = new ChannelDAO();
		dao.insertChannel(channel);
		
		response.sendRedirect("channelList");
		
	}

}
